import java.util.*;

public class Solution1311 {
    public List<String> watchedVideosByFriends(List<List<String>> watchedVideos, int[][] friends, int id, int level) {
        Queue<Integer> queue=new LinkedList<>();
        int t=0;
        queue.offer(id);
        int[] visit=new int[friends.length];
        Arrays.fill(visit,Integer.MAX_VALUE);
        visit[id]=0;
        while (!queue.isEmpty()){
            if (t==level){
                break;
            }
            t++;
            Queue<Integer> queue1=new LinkedList<>();
            while (!queue.isEmpty()){
                int q=queue.poll();
                for (int i : friends[q]) {
                    if (visit[i]==Integer.MAX_VALUE){
                        visit[i]=0;
                        queue1.add(i);
                    }
                }
            }
            queue.addAll(queue1);
        }
        Map<String,Integer> map=new HashMap<>();
        while (!queue.isEmpty()){
            int p=queue.poll();
            for (String s : watchedVideos.get(p)) {
                map.put(s,map.getOrDefault(s,0)+1);
            }
        }
        List<String> list=new ArrayList<>();
        List<Map.Entry<String,Integer>> list1=new ArrayList<>(map.entrySet());
        list1.sort((a,b)-> a.getValue().equals(b.getValue()) ?a.getKey().compareTo(b.getKey()):a.getValue()-b.getValue());
        for (Map.Entry<String, Integer> entry : list1) {
            list.add(entry.getKey());
        }
        return list;
    }

    public static void main(String[] args) {
        System.out.println(new Solution1311().watchedVideosByFriends(Arrays.asList(Arrays.asList("A","B"), Collections.singletonList("C"),Arrays.asList("B","C"), Collections.singletonList("D")),
                new int[][]{{1,2},{0,3},{0,3},{1,2}},0,1));
    }
}
